﻿using System;
using System.Windows.Markup;
using ICodeShare.UI.Converters.Helpers;

namespace ICodeShare.UI.Converters.Markup
{
    #region MarkupExtension
    /// <summary>
    /// 格式化字符串输出转换器,根据对输入进行格式化字符串转换
    /// </summary>
    /// <example>
    /// 1.在xmal文件引用DateConverter类所在命名空间。
    ///    xmlns:cvts="http://schemas.extended.wpf.com/converters"
    /// 2.在xaml文件中指定Binding值的Converter
    /// <Label Content="{Binding Name, Converter={cvts:StringFormatConverter {}Your name is '{0}'.}}"/>
    /// <Label>
    ///     <Label.Content>
    ///         <MultiBinding Converter="{cvts:StringFormatConverter {}Your name is '{0}' and you were born on {1:dd/MM/yyyy}.}">
    ///             <Binding Path="Name"/>
    ///             <Binding Path="Dob"/>
    ///         </MultiBinding>
    ///     </Label.Content>
    /// </Label>
    /// </example>
    [MarkupExtensionReturnType(typeof(StringFormatConverter))]
    public sealed class StringFormatConverterExtension : MarkupExtension
    {
        private static readonly ExceptionHelper exceptionHelper = new ExceptionHelper(typeof(StringFormatConverterExtension));
        private string formatString;

        /// <summary>
        /// Initializes a new instance of the StringFormatConverterExtension class.
        /// </summary>
        public StringFormatConverterExtension()
        {
        }

        /// <summary>
        /// Initializes a new instance of the StringFormatConverterExtension class with the specified format string.
        /// </summary>
        /// <param name="formatString">
        /// The format string for the <see cref="StringFormatConverter"/>.
        /// </param>
        public StringFormatConverterExtension(string formatString)
        {
            this.formatString = formatString;
        }

        /// <summary>
        /// Gets or sets the format string for the <see cref="StringFormatConverter"/>.
        /// </summary>
        [ConstructorArgument("formatString")]
        public string FormatString
        {
            get { return this.formatString; }
            set { this.formatString = value; }
        }

        /// <summary>
        /// Provides an instance of <see cref="StringFormatConverter"/> based on <see cref="FormatString"/>.
        /// </summary>
        /// <param name="serviceProvider">
        /// An object that can provide services.
        /// </param>
        /// <returns>
        /// The instance of <see cref="StringFormatConverter"/>.
        /// </returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            exceptionHelper.ResolveAndThrowIf(this.FormatString == null, "NoFormatString");
            return new StringFormatConverter(this.FormatString);
        }
    }
    #endregion
}
